﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Sumen.Business;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using Sumen.Business.Presenter.Actor;
using Sumen.Business.Presenter.Category;
using Sumen.Business.Presenter.Sys;
using Sumen.Library.Classes.Common;
using Sumen.Library.Classes.Connection;
using Sumen.Library.Enum;
using Sumen.Library.Froms;
using Sumen.Model.Model;

namespace Sumen.GUI.Entities
{
    public partial class Frm_Product_Edit : XtraForm
    {
        Frm_Manager_Picture frm_manager_pic;
        WaitDialogForm waitForm;
        EnumFormStatus _enumFormStatus;

        EnumFormCode _fromCode = EnumFormCode.FrmProduct;
        long _productId;
        long _sorted;
        string _catCode;
        private string urlDesImage = ClsConnection.LocationSave;

        #region Presenter
        private ColorPresenter _colorPresenter;
        private SizePresenter _sizePresenter;
        private ProductTypePresenter _typePresenter;
        private ProductPresenter _productPresenter;
        private ProviderPresenter _providerPresenter;
        private product productinfo;
        private ProductDetailsPresenter _productDetailsPresenter;
        #endregion


        #region Form

        public Frm_Product_Edit()
        {
            InitializeComponent();
            _colorPresenter = new ColorPresenter();
            _sizePresenter = new SizePresenter();
            _typePresenter = new ProductTypePresenter();
            _productPresenter = new ProductPresenter();
            _providerPresenter = new ProviderPresenter();
            _productDetailsPresenter = new ProductDetailsPresenter();
            urlDesImage = Path.Combine(urlDesImage, "SanPham");
        }

        public EnumFormStatus EnumFormStatus
        {
            get { return _enumFormStatus; }
            set
            {
                _enumFormStatus = value;
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    buttonsArray1.btnSua.Enabled = false;
                    buttonsArray1.btnThem.Enabled = true;
                }
                else if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    buttonsArray1.btnSua.Enabled = true;
                    buttonsArray1.btnThem.Enabled = false;
                }
            }
        }

        public long ProductId
        {
            get { return _productId; }
            set { _productId = value; }
        }

        public List<product_details> _listProductDetailsesAddNew;

        public List<product_details> ListProductDetailsesAddNew
        {
            get { return _listProductDetailsesAddNew; }
            set { _listProductDetailsesAddNew = value; }
        }

        private void Frm_Product_Edit_Load(object sender, EventArgs e)
        {
            chkCmbMau.Properties.DataSource = _colorPresenter.GetAll();
            chkCmbSize.Properties.DataSource = _sizePresenter.GetAll();
            cmbChungLoai.Properties.DataSource = _typePresenter.GetAll();
            cmbNhaPhanPhoi.Properties.DataSource = _providerPresenter.GetAll();
            cmbTrangThai.Properties.DataSource = Enum.GetValues(typeof(EnumStatusAccess)).Cast<EnumStatusAccess>().Select(v => v.ToString()).ToList();
            LoadProduct();
        }

        #endregion

        #region Button Event

        private void btnQuanLyHinh_Click(object sender, EventArgs e)
        {
            SplashScreenManager.ShowForm(typeof(WaitForm1));
            try
            {
                product obj = _productPresenter.GetById(_productId) as product;
                if (frm_manager_pic == null)
                {
                    frm_manager_pic = new Frm_Manager_Picture();
                    frm_manager_pic.PProductId = obj.Prod_Product_ID;
                    // SplashScreenManager.CloseForm();
                    frm_manager_pic.ShowDialog();
                }
                else
                {
                    frm_manager_pic.PProductId = obj.Prod_Product_ID;
                    frm_manager_pic.ShowDialog();
                }
                SplashScreenManager.CloseForm();
            }
            catch (Exception ex)
            {
                SplashScreenManager.CloseForm();
                ClsPublic.WriteException(ex);
            }
        }

        private void btnQuayLai_Click(object sender, EventArgs e)
        {
            this.Dispose();

        }

        private void buttonsArray1_btnEventAdd_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    product newProduct = Add();
                    _listProductDetailsesAddNew = _productPresenter.Add(chkCmbMau.EditValue, chkCmbSize.EditValue,
                        newProduct);
                    int proId = _listProductDetailsesAddNew.Count;
                    if (proId > 0)
                    {
                        btnQuanLyHinh.Enabled = true;
                        EnumFormStatus = EnumFormStatus.Modify;
                        _productId = newProduct.Prod_ID;
                        ClsMsgBox.ThongTin("Thêm mới sản phẩm thành công");
                        //ListProductDetailsesAddNew.Clear();
                        if (ClsPublic.SYSTEM_WRITELOG == "1")
                        {
                            SysLogPresenter log = new SysLogPresenter();
                            log.Add(_fromCode, EnumFormStatus.Add, newProduct.Prod_Product_ID, "");
                        }
                    }
                }
            }
        }


        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    product newProduct = Add();
                    int count = _productPresenter.Update(newProduct, ProductId, chkCmbMau.EditValue,
                        chkCmbSize.EditValue);
                    //UpdateProductDetails();
                    if (count == 1)
                    {
                        ClsMsgBox.ThongTin("Cập nhật sản phẩm thành công");
                        if (ClsPublic.SYSTEM_WRITELOG == "1")
                        {
                            SysLogPresenter log = new SysLogPresenter();
                            log.Add(_fromCode, EnumFormStatus.Modify, newProduct.Prod_Product_ID, "");
                        }
                    }
                }
            }

        }

        #endregion

        #region Method

        product Add()
        {
            Nullable<Int32> null32 = null;
            Nullable<Int16> null16 = null;
            product newProduct = new product();
            newProduct.Prod_Product_ID = txtMa.EditValue.ToString();
            newProduct.Prod_CATEGORY_ID = Convert.ToInt32(popupTreeDM.PrimaryKey);
            newProduct.Prod_PROVIDER_ID = cmbNhaPhanPhoi.EditValue + string.Empty;
            newProduct.Prod_Product_Name = txtTen.EditValue + string.Empty;
            newProduct.Prod_PRODUCT_TYPE_ID = cmbChungLoai.EditValue != null
                ? Convert.ToInt32(cmbChungLoai.EditValue)
                : null32;

            newProduct.Prod_Inward_Price = Convert.ToDecimal(txtGiaNhap.EditValue);
            newProduct.Prod_Sale_Price = Convert.ToDecimal(txtGiaLe.EditValue);
            newProduct.Prod_Retails_Price = Convert.ToDecimal(txtGiaSi.EditValue);
            newProduct.Prod_Agent_Price = Convert.ToDecimal(txtGiaDL.EditValue);

            newProduct.Prod_Title = txtTieuDe.EditValue + string.Empty;
            newProduct.Prod_Alias = txtAlias.EditValue + string.Empty;
            newProduct.Prod_Infotext = txtIinfotext.EditValue + string.Empty;
            newProduct.Prod_Published = Convert.ToSByte(cmbTrangThai.ItemIndex);
            newProduct.Prod_Hit = txtLuotXem.EditValue != null ? Convert.ToInt32(txtLuotXem.EditValue) : null32;
            newProduct.Prod_Featured = chkNoiBat.EditValue != null ? Convert.ToInt16(chkNoiBat.EditValue) : null16;
            newProduct.Prod_MetaDesc = txtDesc.EditValue + string.Empty;
            newProduct.Prod_MeteKey = txtKeyword.EditValue + string.Empty;
            newProduct.Prod_Actived = Convert.ToInt32(chkKichHoat.EditValue);
            newProduct.Prod_IsChange = Convert.ToInt32(chkIsChange.EditValue);
            newProduct.Prod_DateModified = DateTime.Now;
            newProduct.Prod_Sorted = _sorted;
            return newProduct;
        }

        void LoadProduct()
        {
            if (_enumFormStatus == EnumFormStatus.Add)
            {
                btnQuanLyHinh.Enabled = false;
                txtMa.Enabled = true;
                txtMa.EditValue = null;
                popupTreeDM.Enabled = true;
                popupTreeDM.PrimaryKey = 0;
                popupTreeDM.PrimaryKey = null;
                cmbNhaPhanPhoi.EditValue = null;
                txtTen.EditValue = null;
                cmbChungLoai.EditValue = null;
                txtGiaNhap.EditValue = null;
                txtGiaLe.EditValue = null;
                txtGiaSi.EditValue = null;
                txtGiaDL.EditValue = null;
                txtTieuDe.EditValue = null;
                txtAlias.EditValue = null;
                txtIinfotext.EditValue = null;
                cmbTrangThai.ItemIndex = 0;
                txtLuotXem.EditValue = null;
                chkNoiBat.EditValue = null;
                txtDesc.EditValue = null;
                txtKeyword.EditValue = null;
                chkCmbSize.EditValue = "";
                chkCmbSize.Text = "";
                chkCmbMau.EditValue = "";
                chkCmbMau.Text = "";
                setImagePictureBox("");
            }
            else if (_enumFormStatus == EnumFormStatus.Modify)
            {
                btnQuanLyHinh.Enabled = true;
                productinfo = (product)_productPresenter.GetById(_productId);
                txtMa.EditValue = productinfo.Prod_Product_ID;
                popupTreeDM.PrimaryKey = productinfo.Prod_CATEGORY_ID;
                popupTreeDM.Enabled = false;
                cmbNhaPhanPhoi.EditValue = productinfo.Prod_PROVIDER_ID;
                txtTen.EditValue = productinfo.Prod_Product_Name;
                cmbChungLoai.EditValue = productinfo.Prod_PRODUCT_TYPE_ID;

                txtGiaNhap.EditValue = productinfo.Prod_Inward_Price;
                txtGiaLe.EditValue = productinfo.Prod_Sale_Price;
                txtGiaSi.EditValue = productinfo.Prod_Retails_Price;
                txtGiaDL.EditValue = productinfo.Prod_Agent_Price;

                txtTieuDe.EditValue = productinfo.Prod_Title;
                txtAlias.EditValue = productinfo.Prod_Alias;
                txtIinfotext.EditValue = productinfo.Prod_Infotext;
                cmbTrangThai.ItemIndex = Convert.ToInt32(productinfo.Prod_Published);
                txtLuotXem.EditValue = productinfo.Prod_Hit;
                chkNoiBat.CheckState = productinfo.Prod_Featured == 1 ? CheckState.Checked : CheckState.Unchecked;
                chkKichHoat.CheckState = productinfo.Prod_Actived == 1 ? CheckState.Checked : CheckState.Unchecked;
                chkIsChange.CheckState = productinfo.Prod_IsChange == 1 ? CheckState.Checked : CheckState.Unchecked;
                txtDesc.EditValue = productinfo.Prod_MetaDesc;
                txtKeyword.EditValue = productinfo.Prod_MeteKey;
                setImagePictureBox(productinfo.Prod_Image);
                chkCmbSize.EditValue = _productDetailsPresenter.GetListSizeIdByProductId(_productId);
                chkCmbMau.EditValue = _productDetailsPresenter.GetListColorIdByProductId(_productId);
            }
        }

        private bool Validation()
        {
            dxErrorProvider1.ClearErrors();
            if (txtMa.EditValue == null || txtMa.EditValue == "")
            {
                dxErrorProvider1.SetError(txtMa, "Vui lòng nhập");
                return false;
            }
            else if (popupTreeDM.PrimaryKey == null)
            {
                dxErrorProvider1.SetError(popupTreeDM, "Vui lòng chọn");
                return false;
            }
            else if (txtTen.EditValue == null || txtTen.EditValue == "")
            {
                dxErrorProvider1.SetError(txtTen, "Vui lòng nhập");
                return false;
            }
            else if (cmbNhaPhanPhoi.EditValue == "" || cmbNhaPhanPhoi.EditValue == "0")
            {
                dxErrorProvider1.SetError(cmbNhaPhanPhoi, "Vui lòng nhập");
                return false;
            }
            else if (cmbChungLoai.EditValue == null)
            {
                dxErrorProvider1.SetError(cmbChungLoai, "Vui lòng nhập");
                return false;
            }
            else if (chkCmbMau.EditValue == "")
            {
                dxErrorProvider1.SetError(chkCmbMau, "Vui lòng nhập");
                return false;
            }
            else if (chkCmbSize.EditValue == "")
            {
                dxErrorProvider1.SetError(chkCmbSize, "Vui lòng nhập");
                return false;
            }
            else if (txtGiaNhap.EditValue == null || txtGiaNhap.EditValue == "")
            {
                dxErrorProvider1.SetError(txtGiaNhap, "Vui lòng nhập");
                return false;
            }
            else if (txtGiaLe.EditValue == null || txtGiaLe.EditValue == "")
            {
                dxErrorProvider1.SetError(txtGiaLe, "Vui lòng nhập");
                return false;
            }

            return true;
        }


        string GetUrlImage(string pImage)
        {
            product obj = _productPresenter.GetById(_productId) as product;

            string url = Path.Combine(urlDesImage, obj.Prod_Product_ID, pImage ?? "");
            return url;
        }

        void setImagePictureBox(string pImageName)
        {
            if (string.IsNullOrEmpty(pImageName))
            {
                pictureEdit1.Image = null;
                return;
            }
            string fullUrl = GetUrlImage(pImageName);
            if (File.Exists(fullUrl))
            {
                FileStream fs = new FileStream(fullUrl, FileMode.Open);
                Image img = Image.FromStream(fs);
                fs.Close();
                pictureEdit1.Image = img;
            }
            else
            {
                pictureEdit1.Image = null;
            }
        }

        #endregion

        private void popupTreeDM_PrimaryKeyChanged(object sender, EventArgs e)
        {
            if (_enumFormStatus == EnumFormStatus.Add)
            {
                //o day tao product id, gan sorted
                CategoryPresenter catPre = new CategoryPresenter();
                category cat = catPre.GetById(popupTreeDM.PrimaryKey);
                if (cat != null)
                {
                    _catCode = cat.Cat_Code;
                    _sorted = _productPresenter.GetNewSortedProduct(cat.Cat_ID);
                    txtMa.EditValue = _catCode + _sorted.ToString().PadLeft(5, '0');
                }
            }


        }



    }
}